<?php

namespace App\Controller;

use App\Model\UserCategory;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\DeleteMapping;

class UserCategoryController extends AbstractController
{
    public function index()
    {
        $list = UserCategory::with('children')->where('user_id', $this->request->user->id)->orderBy('listorder')->orderByDesc('id')->get();
        return $this->success($list);
    }

    public function show($id)
    {
        $row = UserCategory::where('user_id', $this->request->user->id)->findOrFail($id);
        return $this->success($row);
    }

    public function store()
    {
        $data = $this->request->all();
        $data['user_id'] = $this->request->user->id;
        $data['parent_id'] = intval($data['parent_id']);
        $data['listorder'] = intval($data['listorder']);
        return $this->success(UserCategory::create($data));
    }

    public function update($id)
    {
        $data = $this->request->all();
        $userCategory = UserCategory::where('user_id', $this->request->user->id)->findOrFail($id);
        $userCategory->update($data);
        return $this->success($userCategory);
    }

    #[DeleteMapping(path: '{id}')]
    public function destroy($id)
    {
        $userCategory = UserCategory::where('user_id', $this->request->user->id)->findOrFail($id);
        $ret = $userCategory->delete();
        return $this->success($ret);
    }
}
